import time

from selenium.webdriver import ActionChains

from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement, KeyCode
from libs.window import AdsWindow
from libs.task_helper import TaskHelper


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Charge')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    # 启动窗口
    driver = AdsWindow(user_id).open(False)
    action = WebDriverAction(driver)
    movement = Movement(driver)
    image_tool = ImageTool(driver)
    ac = ActionChains(driver)
    ac.reset_actions()

    try:
        # 进入游戏
        game = Game(driver, user_id)
        game.enter_game(user_id)
        log.info('charge start')
        energy = game.get_energy()
        if energy > 450:
            TaskHelper(user_id).charge(delay_seconds=60 * 60 * 3)
        else:
            action.handle_dialog()
            game.snapshot(user_id, 'charge_start')
            # 先判断是不是已经在指定位置
            sona_charge_image = "saona_station.png"
            charge_loc = image_tool.find_target(sona_charge_image)
            if charge_loc is None:
                action.goto_saona()
                action.wait_page_loaded()
                for loop in range(100):
                    charge_loc = image_tool.find_target(sona_charge_image)
                    if charge_loc is not None:
                        print('found charge station')
                        movement.send_key_up(KeyCode.UP)
                        break
                    movement.send_key_down(KeyCode.UP)
                    time.sleep(0.1)
                action.handle_dialog()
            if charge_loc is None:
                log.info(f"charge station not found")
            movement.keep_move_up(3)
            charge_loc = image_tool.find_target(sona_charge_image)
            charge_x, charge_y = charge_loc
            ac.reset_actions()
            old_energy = game.get_energy()
            ac.move_by_offset(charge_x+35, charge_y+20).click().perform()
            time.sleep(5)
            new_energy = game.get_energy()
            game.snapshot(user_id, 'change_end')
            if new_energy - old_energy >= 350:
                log.info(f"charge success")
                # 六小时后再次执行
                task_helper.charge(delay_seconds=60*60*8)
            else:
                delay_seconds = 60 * 60
                log.info(f"charge fail, retry after {delay_seconds} seconds")
                task_helper.charge(delay_seconds)
        task_helper.task_success()
    except Exception as e:
        task_helper.charge(retry=True)
        task_helper.task_fail()
        raise e
